import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { getReportRecordList } from '@/business/services/user/userInfo';
import { ReportRecordItem } from '@/business/services/user/userInfo/types';

/**
 * @description 我的举报记录列表
 * @author Alisa
 */

type RequestFunction = (pageParams: PageParams, isAppend?: boolean) => Promise<void>;

type State = {
  // 我的举报记录列表
  reportList: ReportRecordItem[];
  // 分页信息
  pageInfo: PageInfo;
  // 数据是否加载完成
  isDataLoaded: boolean;
  // 是否有更多数据
  hasMore: boolean;
};

type Actions = {
  // 获取举报记录列表
  getReportList: RequestFunction;
  // 上拉加载
  handlePullUp: RequestFunction;
  // 下拉刷新
  handlePullDown: RequestFunction;
};

const initialState: State = {
  // 我的举报记录列表
  reportList: [],
  // 分页信息
  pageInfo: {},
  // 数据是否加载完成
  isDataLoaded: true,
  // 是否有更多数据
  hasMore: true,
};

export const reportRecordStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取举报记录列表
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     */
    getReportList: async (pageParams: PageParams, isAppend = false) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          ...pageParams,
        };
        const result = await getReportRecordList(requestData);
        if (result) {
          set((state) => {
            if (isAppend) {
              state.reportList = [...state.reportList, ...(result?.data || [])];
            } else {
              state.reportList = result?.data || [];
            }
            state.pageInfo = {
              pageIndex: pageParams?.current,
              pageSize: pageParams?.size,
              totalCount: result?.totalCount,
            };
            state.hasMore =
              (pageParams?.current as number) * (pageParams?.size as number) < result?.totalCount;
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 上拉加载
     * @param pageParams 分页
     */

    handlePullUp: async (pageParams: PageParams) => {
      const newPageInfo = { ...pageParams, current: Number(pageParams.current) + 1 };
      await get().getReportList(newPageInfo, true);
    },

    /**
     * 下拉刷新
     * @param pageInfo 分页
     */
    handlePullDown: async (pageParams: PageParams) => {
      const newPageInfo = { ...pageParams };
      await get().getReportList(newPageInfo, false); // 传递 isAppend = false
    },
  })),
);
